The this
keyword in JavaScript refers to the object that is currently executing a function or
method. Its value is determined by how a function is called, not where it is defined.
In the global context, this
refers to the global object (window in browsers).
console.log(this); // Window object (in browsers)
In a regular function, this
refers to the global object (non-strict mode) or undefined
(strict mode).
function myFunction() {
console.log(this);
}
myFunction(); // Window object (non-strict mode) or undefined (strict mode)
When a function is called as a method of an object, this
refers to the object.
const person = {
firstName: "John",
lastName: "Doe",
fullName: function() {
return this.firstName + " " + this.lastName;
}
};
console.log(person.fullName()); // John Doe
In event handlers, this
refers to the element that received the event.
document.getElementById("myButton").addEventListener("click", function() {
console.log(this); // The button element
});
Arrow functions do not have their own this
binding. They inherit this
from the parent
scope at the time they are defined.
const obj = {
value: 42,
regularFunction: function() {
console.log(this.value); // 42
},
arrowFunction: () => {
console.log(this.value); // undefined
}
};
obj.regularFunction();
obj.arrowFunction();
You can explicitly set the value of this
using call()
, apply()
, and
bind()
methods.
function greet() {
return "Hello, " + this.name;
}
const person1 = { name: "Alice" };
const person2 = { name: "Bob" };
console.log(greet.call(person1)); // Hello, Alice
console.log(greet.apply(person2)); // Hello, Bob
const greetPerson1 = greet.bind(person1);
console.log(greetPerson1()); // Hello, Alice
For more detailed information, you can check out resources like W3Schools[^1^][1] and MDN Web Docs[^2^][2].